package com.realphim.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.realphim.app.adapter.AdapterFeaturePager;
import com.realphim.app.adapter.AdapterGridCategory;
import com.realphim.app.component.LayoutCategory;
import com.realphim.app.model.ModelCategory;
import com.realphim.app.model.ModelPhim;
import com.realphim.app.util.CommonDefine;
import com.realphim.app.util.CommonUtil;
import com.realphim.app.util.JSONParser;
import com.realphim.app.util.MyCache;

public class ActivityMain extends FragmentActivity implements CommonDefine,
        android.view.View.OnClickListener, IXListViewListener {

    private final String TAG = "ActivityMain";

    private final int TIME_OUT = 10;

    public static Context _context;

    private ViewPager mPager;

    private AdapterFeaturePager adapterFeaturePager;

    private int currentFeature = 0;

    private int timeChange = 0;

    private List<LayoutCategory> listLayoutCategory;

    private LinearLayout llCategory;

    public SlidingMenu menu;

    private ImageView ivMenu, ivSearch;

    private EditText edtSearch;

    private XListView lvSearch;

    private ProgressBar pbLoadSearch;

    private LinearLayout llHome;

    private RelativeLayout rlPhim;

    private boolean isSearching = false;

    private boolean clickSearchable = true;

    private int start = 0;

    private int item_per_page;

    private List<ModelPhim> listPhimCate = new ArrayList<ModelPhim>();

    private AdapterGridCategory adapterCate;

    private int posCover = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        setContentView(R.layout.activity_main);

        _context = this;
        item_per_page = getResources().getInteger(R.integer.item_per_page);
        listLayoutCategory = new ArrayList<LayoutCategory>();
        listLayoutCategory.add(new LayoutCategory(_context,
                getString(R.string.film_view_alot), SERVICE_GET_LIST_FILM
                        + ServiceParam.ORDER_BY + "=view_count_week"));
        listLayoutCategory.add(new LayoutCategory(_context,
                getString(R.string.film_new_update), SERVICE_GET_LIST_FILM
                        + ServiceParam.ORDER_BY + "=update_time"));
        listLayoutCategory.add(new LayoutCategory(_context,
                getString(R.string.film_new_cinema), SERVICE_GET_LIST_FILM
                        + "is_cinema=1&order_by=id"));

        initPager();

        initView();

        initMenu();
    }

    private void initMenu() {
        menu = new SlidingMenu(this);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setShadowDrawable(R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.menu_frame);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.menu_frame, new FragmentLeftMenu()).commit();

        ivMenu = (ImageView) findViewById(R.id.ivMenu);
        ivMenu.setOnClickListener(this);
    }

    private void initPager() {
        mPager = (ViewPager) findViewById(R.id.pager);
        adapterFeaturePager = new AdapterFeaturePager(
                getSupportFragmentManager());
        mPager.setAdapter(adapterFeaturePager);
        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                timeChange = 0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        threadChangeFeature.start();
    }

    public void initView() {
        llCategory = (LinearLayout) findViewById(R.id.llCategory);
        for (int i = 0; i < listLayoutCategory.size(); i++) {
            llCategory.addView(listLayoutCategory.get(i));
            listLayoutCategory.get(i).init();
        }
        listLayoutCategory.get(0).tvCategoryName.performClick();

        ivSearch = (ImageView) findViewById(R.id.ivSearch);
        ivSearch.setOnClickListener(this);

        llHome = (LinearLayout) findViewById(R.id.llHome);

        rlPhim = (RelativeLayout) findViewById(R.id.rlPhim);

        edtSearch = (EditText) findViewById(R.id.edtSearch);

        lvSearch = (XListView) findViewById(R.id.lvSearch);

        adapterCate = new AdapterGridCategory(_context, listPhimCate);
        lvSearch.setAdapter(adapterCate);
        lvSearch.setPullLoadEnable(false);
        lvSearch.setPullRefreshEnable(false);
        lvSearch.setXListViewListener(this);

        pbLoadSearch = (ProgressBar) findViewById(R.id.pbLoadSearch);

        edtSearch.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if (edtSearch.getText().toString().equals("")) {
                        Toast.makeText(_context,
                                "Bạn chưa nhập từ khóa tìm kiếm",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        if (clickSearchable) {
                            clickSearchable = false;
                            rlPhim.setVisibility(View.VISIBLE);
                            llHome.setVisibility(View.GONE);
                            start = 0;
                            posCover = 0;
                            listPhimCate = new ArrayList<ModelPhim>();
                            adapterCate.notifyDataSetChanged();
                            pbLoadSearch.setVisibility(View.VISIBLE);
                            CommonUtil.hideSoftWareInput(ActivityMain.this);
                            new AsyntaskSearch()
                                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }
                }
                return false;
            }
        });
    }

    private Thread threadChangeFeature = new Thread(new Runnable() {

        public void run() {
            while (timeChange >= 0) {
                timeChange += 1;
                // Log.i("TIME", "" + timeChange);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (timeChange == TIME_OUT) {
                    mPager.post(new Runnable() {

                        @Override
                        public void run() {
                            changeFragment();
                        }
                    });

                }
            }
        }
    });

    private void changeFragment() {
        if (currentFeature < MyCache.getInstance().listPhimFeature.size() - 1) {
            currentFeature++;
        } else {
            currentFeature = 0;
        }
        mPager.setCurrentItem(currentFeature, true);
        ;
    }

    @Override
    protected void onDestroy() {
        threadChangeFeature.interrupt();
        threadChangeFeature = null;
        System.exit(0);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.ivMenu:
            if (!menu.isMenuShowing()) {
                menu.showMenu();
            }
            break;

        case R.id.ivSearch:
            if (isSearching == false) {
                isSearching = true;
                edtSearch.setVisibility(View.VISIBLE);
                CommonUtil.showSoftWareInput(_context, edtSearch);
                edtSearch.startAnimation(AnimationUtils.loadAnimation(_context,
                        R.anim.push_left_in));
                ivSearch.setImageResource(R.drawable.cancel);
                edtSearch.requestFocus();
                edtSearch.setFocusable(true);
                edtSearch.setFocusableInTouchMode(true);
            } else {
                closeSearchForm();
            }
            break;
        }
    }

    private void closeSearchForm() {
        isSearching = false;
        // Log.i(TAG, "vuongtm Hide keyboard");
        CommonUtil.hideSoftWareInput(this);
        edtSearch.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.push_left_out));
        ivSearch.setImageResource(R.drawable.ic_search);
        edtSearch.setVisibility(View.INVISIBLE);
        rlPhim.setVisibility(View.GONE);
        llHome.setVisibility(View.VISIBLE);
        start = 0;
        posCover = 0;
        listPhimCate = new ArrayList<ModelPhim>();
        adapterCate.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if (menu.isMenuShowing()) {
            menu.showContent();
        } else {
            if (isSearching) {
                closeSearchForm();
            } else {
                finish();
            }
        }
    }

    private class AsyntaskSearch extends AsyncTask<Integer, Integer, Boolean> {

        private List<ModelPhim> listTemp = new ArrayList<ModelPhim>();

        @Override
        protected Boolean doInBackground(Integer... params) {
            boolean result = false;
            try {

                String strUrl = SERVICE_GET_LIST_FILM + ServiceParam.KEY_WORD
                        + "=" + edtSearch.getText().toString() + "&"
                        + ServiceParam.LIMIT + "=" + item_per_page + "&"
                        + ServiceParam.START + "=" + start + "&"
                        + ServiceParam.ORDER_BY + "=view_count";
                Log.v(TAG, strUrl);
                String jsonResult = new JSONParser().getJSONFromUrl(strUrl,
                        METHOD_GET, null);
                Log.i(TAG, jsonResult);
                JSONArray arrResult = new JSONObject(jsonResult)
                        .getJSONArray("data");

                for (int i = 0; i < arrResult.length(); i++) {
                    JSONObject objPhim = arrResult.getJSONObject(i);
                    ModelPhim myPhim = new ModelPhim();
                    myPhim.id = objPhim.getInt(KeyPhim.id);
                    myPhim.title = objPhim.getString(KeyPhim.title);
                    myPhim.titleTranslate = objPhim
                            .getString(KeyPhim.title_translate);
                    myPhim.imageUrl = objPhim.getString(KeyPhim.image);
                    myPhim.thumbnailUrl = objPhim.getString(KeyPhim.thumbnail);
                    myPhim.description = objPhim.getString(KeyPhim.description);
                    myPhim.lastEp = objPhim.getInt(KeyPhim.last_episode);
                    myPhim.maxEp = objPhim.getInt(KeyPhim.max_episode);
                    myPhim.isHD = objPhim.getInt(KeyPhim.is_hd);
                    myPhim.imb = objPhim.getString(KeyPhim.imdb);
                    myPhim.publishYear = objPhim
                            .getString(KeyPhim.publish_year);
                    myPhim.duration = objPhim.getInt(KeyPhim.duration);
                    myPhim.isFeature = objPhim.getInt(KeyPhim.is_featured);
                    myPhim.isCinema = objPhim.getInt(KeyPhim.is_cinema);
                    myPhim.rate = objPhim.getString(KeyPhim.rate);
                    myPhim.director = objPhim.getString(KeyPhim.director);
                    myPhim.viewFake = objPhim.getString(KeyPhim.view_fake);
                    myPhim.label = objPhim.getString(KeyPhim.label);
                    myPhim.actors = objPhim.getString(KeyPhim.actors);
                    myPhim.nation = objPhim.getString(KeyPhim.nation);
                    myPhim.tag = objPhim.getString(KeyPhim.tags);
                    myPhim.uploadBy = objPhim.getString(KeyPhim.upload_by);
                    myPhim.creatDate = objPhim.getString(KeyPhim.created_date);
                    myPhim.viewCount = objPhim.getString(KeyPhim.view_count);
                    myPhim.viewCountMonth = objPhim
                            .getString(KeyPhim.view_count_month);
                    myPhim.viewCountWeek = objPhim
                            .getString(KeyPhim.view_count_week);

                    JSONArray arrCategory = objPhim
                            .getJSONArray(KeyPhim.category);
                    for (int j = 0; j < arrCategory.length(); j++) {
                        JSONObject objCate = arrCategory.getJSONObject(j);
                        ModelCategory myCate = new ModelCategory();
                        myCate.id = objCate.getInt(KeyCategory.id);
                        myCate.title = objCate.getString(KeyCategory.title);
                        myPhim.listCategories.add(myCate);
                    }

                    listTemp.add(myPhim);

                    result = true;

                }
            } catch (Exception e) {
                Log.e(TAG, e.toString() + "");
                result = false;
            }
            return result;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            lvSearch.stopLoadMore();
            clickSearchable = true;
            if (result) {
                pbLoadSearch.setVisibility(View.GONE);
                start += listTemp.size();
                for (int i = 0; i < listTemp.size(); i++) {
                    listPhimCate.add(listTemp.get(i));
                }
                adapterCate = new AdapterGridCategory(_context, listPhimCate);
                adapterCate.notifyDataSetChanged();
                Log.d("LIST PHIM SIZE", "" + listPhimCate.size());
                lvSearch.setAdapter(adapterCate);
                if (listPhimCate.size() > 0) {
                    new AsyntaskLoadCover()
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } else {
                    Toast.makeText(_context, "Không tìm thấy phim",
                            Toast.LENGTH_SHORT).show();
                }
                if (listTemp.size() < item_per_page) {
                    lvSearch.setPullLoadEnable(false);
                } else {
                    lvSearch.setPullLoadEnable(true);
                }

            } else {
                showDialogNoConnection();
            }
        }
    }

    private class AsyntaskLoadCover extends AsyncTask<String, String, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO Auto-generated method stub
            InputStream iStream = null;
            URL url;
            String name;
            try {

                url = new URL(listPhimCate.get(posCover).thumbnailUrl);
                name = listPhimCate.get(posCover).title;

                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.connect();
                iStream = urlConnection.getInputStream();
                File cacheDirectory = getCacheDir();
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
                        + name + ".png");
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                Bitmap b = BitmapFactory.decodeStream(iStream);
                b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);

                Bitmap result = Bitmap.createScaledBitmap(b, 200, 300, true);
                fOutStream.flush();
                fOutStream.close();
                b.recycle();
                return result;

            } catch (Exception e) {
                Log.e("LoadImage", e.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            listPhimCate.get(posCover).thumbnailBitmap = result;
            adapterCate.notifyDataSetChanged();
            if (posCover < listPhimCate.size() - 1) {
                posCover++;
                new AsyntaskLoadCover()
                        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        }
    }

    private void showDialogNoConnection() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(_context);
        dialog.setTitle("Connection");
        dialog.setMessage("Can not connect to server");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLoadMore() {
        new AsyntaskSearch().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

}
